<?php
declare(strict_types=1);


namespace App\Fastapp\Mapper;

use App\Fastapp\Model\FastappCategory;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;
use Mine\MineCollection;

/**
 * 分类列表Mapper类
 */
class FastappCategoryMapper extends AbstractMapper
{
    /**
     * @var FastappCategory
     */
    public $model;

    public function assignModel()
    {
        $this->model = FastappCategory::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        if (isset($params['scene']) && filled($params['scene'])) {
            $query->whereIn('scene', $params['scene']);
        }

        // 名称
        if (isset($params['name']) && filled($params['name'])) {
            $query->where('name', '=', $params['name']);
        }

        // 上级
        if (isset($params['parent_id']) && filled($params['parent_id'])) {
            $query->where('parent_id', '=', $params['parent_id']);
        }

        // 1显示
        if (isset($params['status']) && filled($params['status'])) {
            $query->where('status', '=', $params['status']);
        }

        // 调用代码
        if (isset($params['code']) && filled($params['code'])) {
            $query->where('code', '=', $params['code']);
        }

        return $query->orderByDesc('id');
    }

    public function tree(array $param): array
    {
        $query = $this->model::query();
        if (!empty($param['scene'])) $query->whereIn('scene', $param['scene']);
        if (isset($param['parent_id'])) $query->where(['parent_id' => $param['parent_id']]);
        $res = new MineCollection($query->get()->map(function ($item) {
            return [
                'id' => $item->id,
                'label' => fastapp_lang_text($item->name),
                'parent_id' => $item->parent_id,
                'value' => $item->id,
            ];
        }));
        return $res->toTree();
    }

    public function select(array $param): array
    {
        $query = $this->model::query();
        if (!empty($param['scene'])) $query->whereIn('scene', $param['scene']);
        if (isset($param['parent_id'])) $query->where(['parent_id' => $param['parent_id']]);
        return $query->select(['id', 'name', 'code'])->get()->map(function ($item) {
            $item->name = fastapp_lang_text($item->name);
            return $item;
        })->toarray();
    }
}